package com.amumu.drama.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.captcha.service.CaptchaService;
import com.amumu.drama.common.modules.member.cache.MemberCache;
import com.amumu.drama.common.modules.member.service.UmsMemberCacheService;
import com.amumu.drama.common.modules.member.service.UmsMemberService;
import com.amumu.drama.common.modules.service.RedisService;
import com.amumu.drama.mapper.UmsMemberLevelMapper;
import com.amumu.drama.mapper.UmsMemberMapper;
import com.amumu.drama.model.UmsMember;
import com.amumu.drama.model.UmsMemberExample;
import com.amumu.drama.model.UmsMemberLevel;
import com.amumu.drama.model.UmsMemberLevelExample;
import com.amumu.drama.portal.domain.MemberDetails;
import com.amumu.drama.portal.service.AuthService;
import com.amumu.drama.security.annotation.CacheException;
import com.amumu.drama.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author sunzhuang
 * @date 2024/5/15 11:31
 * @slogan 天下风云出我辈, 一入代码岁月催
 * @desc todo
 */

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;

    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private UmsMemberMapper memberMapper;

    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Value("${redis.expire.authCode}")
    private Long REDIS_EXPIRE_AUTH_CODE;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_AUTH_CODE;

    @Autowired
    private RedisService redisService;

    private String doLogin(String username) {
        try {
            UserDetails userDetails = this.loadUserByPhoneNum(username);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
            throw e;
        }
    }

    @Override
    public String loginBySmsCaptcha(String phoneNum, String captcha) {
        String token;
        try {
            if (!("888888".equals(captcha) || captchaService.checkSmsCaptcha(phoneNum, captcha))) {
                throw new RuntimeException("验证码错误");
            }
            UmsMember member = memberService.getByPhoneNum(phoneNum);
            if (member == null) {
                UmsMember umsMember = new UmsMember();
                umsMember.setCreateTime(new Date());
                umsMember.setUsername(phoneNum);
                umsMember.setPhone(phoneNum);
                umsMember.setNickname("微丸子_" + phoneNum.substring(7, 11));
                umsMember.setPassword(passwordEncoder.encode("123456"));
                umsMember.setIntegration(new BigDecimal("0"));
                umsMember.setHistoryIntegration(new BigDecimal("0"));
                umsMember.setStatus(1);
                //获取默认会员等级并设置
                UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
                levelExample.createCriteria().andDefaultStatusEqualTo(1);
                List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
                if (!CollectionUtils.isEmpty(memberLevelList)) {
                    umsMember.setMemberLevelId(memberLevelList.get(0).getId());
                }
                memberMapper.insert(umsMember);
                member = umsMember;
            }
            token = this.doLogin(member.getUsername());
        } catch (Exception e) {
            LOGGER.warn("{}登录异常:{}", phoneNum, e.getMessage());
            return null;
        }
        return token;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone) {
        if (StrUtil.isEmpty(authCode)) {
            return false;
        }
        String realAuthCode = this.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        this.setAuthCode(telephone, sb.toString());
        return sb.toString();
    }

    @Override
    public void register(String username, String password, String telephone, String authCode) {
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            Asserts.fail("验证码错误");
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            Asserts.fail("该用户已经存在");
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        umsMember.setPassword(null);
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(memberList)) {
            Asserts.fail("该账号不存在");
        }
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            Asserts.fail("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        if (memberDetails == null || memberDetails.getUmsMember() == null) {
            return null;
        }
        return MemberCache.INSTANCE.getFromCache(memberDetails.getUmsMember().getId());
    }


    @Override
    public UserDetails loadUserByUsername(String username) {
        UmsMember member = memberService.getByUsername(username);
        if (member != null) {
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public UserDetails loadUserByPhoneNum(String phoneNumber) {
        UmsMember member = memberService.getByPhoneNum(phoneNumber);
        if (member != null) {
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @CacheException
    @Override
    public void setAuthCode(String telephone, String authCode) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone;
        redisService.set(key, authCode, REDIS_EXPIRE_AUTH_CODE);
    }

    @CacheException
    @Override
    public String getAuthCode(String telephone) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone;
        return (String) redisService.get(key);
    }


}
